package com.auto.learning.tools;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;

import com.auto.learning.R;
import com.auto.learning.bean.VersionInfo;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.listener.DialogListener;
import com.auto.learning.net.HttpCommonInfo;
import com.auto.learning.net.HttpHelper;
import com.auto.learning.view.CommonAlertDialog;
import com.auto.learning.view.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class CheckUpdateThread extends AsyncTask<Void, Void, VersionInfo> {

	Context context;
	int position = 0;   //1:代表在Mainactivity，0:代表在设置页面FavorSetActivity
	int versionCode = -1;
	String versionName = "";
	VersionInfo info;
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			
		};
	};

	public CheckUpdateThread(Context context,int position) {
		this.context = context;
		this.position = position;
	}

	@Override
	protected void onPreExecute() {
		try {
			PackageManager pm = context.getPackageManager();
			PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(),PackageManager.GET_CONFIGURATIONS);
			versionCode = packageInfo.versionCode;
			versionName = packageInfo.versionName;
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onPreExecute();
	}

	@Override
	protected VersionInfo doInBackground(Void... p) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpCommonInfo.RESULT_CODE, String.valueOf(versionCode)));
		params.add(new BasicNameValuePair("type", "1"));
		try {
			HttpEntity entity = HttpHelper.getInfoByPost(HttpCommonInfo.check_update, params, context);
			String result = HttpHelper.entity2String(entity);
			Log.d("VersionInfo", result);
			JSONObject resultJsonObject = new JSONObject(result);
			JSONObject resultDetail = resultJsonObject.getJSONObject(HttpCommonInfo.RESULT);
			int resultCode = resultDetail.getInt(HttpCommonInfo.RESULT_CODE);
			if (resultCode == 0) {
				info = new Gson().fromJson(resultJsonObject.getString(HttpCommonInfo.DATA),new TypeToken<VersionInfo>() {}.getType());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return info;
	}

	protected void onPostExecute(final VersionInfo result) {
		boolean hasShowNewVersionDialog = (boolean) SharedPreferencesUtils.getParam(context, "new_version_"+ versionCode, false);
		if ((position == 1 && !hasShowNewVersionDialog) || position == 0) {
			if (result != null) {
				if (result.code == -1) {
					if (position == 0) {
						CommonMethod.makeNotice(context, "当前已经是最新版本了");
					}
				} else {
					CommonAlertDialog alertDialog = new CommonAlertDialog(context);
					alertDialog.setDialogTextPosition(1);
					alertDialog.setTextMessage(result.verContent);
					alertDialog.setShowTitle(true);
					alertDialog.setTilte("更新提醒");
					String[] a = { "安装", "取消" };
					alertDialog.setBtns(new DialogListener() {
	
						@Override
						public void okButtonClick(Dialog dialog) {
							dialog.dismiss();
							switch (CommonMethod.getNetworkState(context)) {
							case 1:
								SharedPreferencesUtils.setParam(context, "new_version_"+ versionCode, true);
								CommonMethod.makeNotice(context, "后台正在更新最新APP");
								EventBus.getEventBus("update_apk").post(result);
								dialog.dismiss();
								
								break;
							case 2:
								SharedPreferencesUtils.setParam(context, "new_version_"+ versionCode, true);
								CommonAlertDialog ad = new CommonAlertDialog(context);
								ad.setTextMessage("当前为移动网络，是否继续下载？");
								ad.setShowTitle(true);
								ad.setTilte("更新提醒");
								String[] aa = { "继续", "取消" };
								ad.setBtns(new DialogListener() {
	
									@Override
									public void okButtonClick(Dialog dialog) {
										dialog.dismiss();
										handler.postDelayed(new Runnable() {
	
											@Override
											public void run() {
												CommonMethod.makeNotice(context,"后台正在更新最新APP");
												EventBus.getEventBus("update_apk").post(result);
											}
										}, 500);
	
									}
	
									@Override
									public void cancelButtonClick(Dialog dialog) {
										dialog.dismiss();
									}
	
									@Override
									public void otherButtonClick(Dialog dialog) {
										dialog.dismiss();
									}
								}, aa);
								ad.show();
								break;
							case 0:
								CommonMethod.makeNotice(context,context.getResources().getString(R.string.connect_err_io));
								break;
							}
						}
	
						@Override
						public void cancelButtonClick(Dialog dialog) {
							SharedPreferencesUtils.setParam(context, "new_version_"+ versionCode, true);
							dialog.dismiss();
						}
	
						@Override
						public void otherButtonClick(Dialog dialog) {
							dialog.dismiss();
						}
					}, a);
					alertDialog.show();
				}
			}
		}
	};
}